<?php

/**
 * C2DMRegistrationHelper takes care of (un-)registering FHPI clients from
   receiving C2DM messages by the FHPI service.
 *
 * @author Michael Mitteregger <Michael.Mitteregger.ITM09@fh-joanneum.at>
 */
class C2DMRegistrationHelper {
    
	private $clientRegistrationId;
	private $mode;	
	public $status;
	    
    /**
     * The constructor expects all data necessary to register/unregister a device.
     * 
     * @param String $registrationId The C2DM registration id issued to the client by Google's C2DM service after registering.
     */
    function __construct($key, $themode, $registrationId){
		$this->clientRegistrationId = $registrationId;
		$this->mode = $themode;
		
		if(!isValidApp($key)){
            $this->status = "INVALID_KEY";
        } else if ($this->clientRegistrationId == null){
            $this->status = "INCOMPLETE_DATA";
        } else if (strlen($this->clientRegistrationId) <= 0){
            $this->status = "INVALID_DATA";
        } else if (!(strcasecmp($this->mode, "R") == 0 || strcasecmp($this->mode, "U") == 0)) {
			$this->status = "INVALID_DATA";
		} else {
            $this->status = "OK";
        }
    }
	
	function perform() {
		if($this->status == "OK") {
			if (strcasecmp($this->mode, "R") == 0){
				$this->register();
			}
			if (strcasecmp($this->mode, "U") == 0) {
				$this->unregister();
			}
		}
	}
	
	/**
	 * Registers the client so it can receive C2DM messages by the FHPI service.
	 */
	function register()	{
		include 'config.php';
		$id = mysqli_real_escape_string($db, $this->clientRegistrationId);
		$query = "INSERT INTO c2dmclients (registration_id) VALUES ('$id');";		
		mysqli_query($db, $query);
	}
	/**
	 * Unregisters the client from receiving C2DM messages by the FHPI service.
	 */
	function unregister() {
		include 'config.php';
		$id = mysqli_real_escape_string($db, $this->clientRegistrationId);
		$query = "DELETE FROM c2dmclients WHERE registration_id = '$id';";		
		mysqli_query($db, $query);	
	}
}

?>